//
//  YYTabBar.swift
//  SinaStatuse（新浪微博）
//
//  Created by 李贤立 on 16/4/8.
//  Copyright © 2016年 李贤立. All rights reserved.
//

import UIKit
//// 1.定义代理方法
//protocol YYTabBarDelegate : NSObjectProtocol {
//    // 2.定义代理方法
//    func composeBtnDidClick(YYTabBar:YYTabBar)
//}
class YYTabBar: UITabBar {
    
    // 1.定义闭包属性
    var composeClosure: (() -> ())?
    // 3.定义代理属性
//    var delegate: YYTabBarDelegate?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 定义tabBar的个数
        let count = 5
        // 定义tabBar序号
        var index = 0
        // 计算得到tabBar的宽度
        let width = frame.size.width / CGFloat(count)
        // 根据frame平移方法，预先设定初始化的frame
        let newFrame = CGRect(x: 0, y: 1, width: width, height: frame.size.height)
        
        // 循环遍历
        for subview in subviews {
//            print("\(subview)")
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                // 根据序号设置frame
//                subview.frame = CGRect(x: CGFloat(index) * width, y: 1, width: width, height: frame.size.height)
                // 方法二，frame可以平移
                subview.frame = CGRectOffset(newFrame, CGFloat(index) * width, 0)
                // 跳过中间序号，留出空间给加号按钮
//                index += 1
//                if index == 2 {
//                    index = 3
//                }
                // 方法二
                index += index == 1 ? 2 : 1
            }
        }
        // 添加加号按钮
        composeBtn.frame = CGRect(x: 2 * width, y: 1, width: width, height: frame.size.height)
        
    }
    // 监听按钮绑定
    @objc private func composeBtnDidClick() {
        // 2.调用执行闭包
        composeClosure?()
    }
    // MARK: 懒加载加号按钮
    private lazy var composeBtn: UIButton = {
        let btn = UIButton()
        // 设置图片
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        // 绑定事件
        btn.addTarget(self, action: #selector(YYTabBar.composeBtnDidClick), forControlEvents: UIControlEvents.TouchUpInside)
        // 添加按钮
        self.addSubview(btn)
        return btn
    }()

}
